package org.fnzn.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.fnzn.bean.*;
import org.fnzn.bean.vo.User;
import org.fnzn.core.CommonConstant;
import org.fnzn.core.Constants;
import org.fnzn.core.Page;
import org.fnzn.core.Result;
import org.fnzn.dao.FnglStaffMapper;
import org.fnzn.dao.LrdUserMapper;
import org.fnzn.dao.LrdUserroleMapper;
import org.fnzn.service.*;
import org.fnzn.service.base.AbstractService;
import org.fnzn.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class FnglStaffServiceImpl extends AbstractService<FnglStaff> implements FnglStaffService {

    @Autowired(required = false)
    private FnglStaffMapper fnglStaffMapper;
    @Autowired
    private LrdUserService lrdUserService;
    @Autowired
    private FnglProjectService fnglProjectService;
    @Autowired
    private UserRoleServiceImpl userRoleServiceImpl;
    @Autowired(required = false)
    private LrdUserroleMapper lrdUserroleMapper;
    @Autowired(required = false)
    private LrdUserMapper lrdUserMapper;
    @Override
    public Result findFnglStaff(FnglStaff fnglStaff, Page page) {
        if(page.getLimit()!=null&& page.getPage()!=0){
            Condition condition = new Condition(FnglStaff.class);
            Example.Criteria criteria=condition.createCriteria();
            // 根据删除状态查询列表
            criteria.andEqualTo("delFlag",0);
            // 根据人员姓名查询
            if(!StringUtil.isEmpty(fnglStaff.getRealName())){
                criteria.andLike("realName","%"+fnglStaff.getRealName()+"%");
            }
            // 根据人员所属项目查询
            if(!StringUtil.isEmpty(fnglStaff.getProjectId())){
                criteria.andEqualTo("projectId",fnglStaff.getProjectId());
            }
            // 根据人员所属角色处查询
            if(!StringUtil.isEmpty(fnglStaff.getRoleId())){
                criteria.andEqualTo("roleId",fnglStaff.getRoleId());
            }
            // 获取到当前登录用户所属角色
            User user = CommonUtil.getUser();
            LrdUserrole userrole = userRoleServiceImpl.findBy("userId",user.getUser_id());
            String roleId = userrole.getRoleId();
            // 根据用户手机号获取到人员信息
            FnglStaff fnglstaff = findBy("phone", user.getUser_id());
            // 如果当前是项目经理登录，那么可以看到所属于自己的销售人员以及自己
            if(roleId.equals(Constants.MANAGER_ROLE)){
                criteria.andEqualTo("blamer",fnglstaff.getStaffId());
            }
            // 如果当前是销售人员登录，那么只能看到自己的信息
            if(roleId.equals(Constants.SALESMAN_ROLE)){
                criteria.andEqualTo("phone",user.getUser_id());
            }
            condition.setOrderByClause("create_time desc");
            PageHelper.startPage(page.getPage(),page.getLimit(), true);
            List<FnglStaff> list = findByCondition(condition);
            page.setRows(list);
            page.setTotal(new PageInfo(list).getTotal());
            return ResultGenerator.genSuccessResult(page);
        }
        return ResultGenerator.genFailResult("查询失败");
    }

    @Override
    @Transactional
    public Result insertFnglStaff(FnglStaff fnglStaff) {
        if(fnglStaff!=null){
            fnglStaff.setStaffId(StringUtil.getUUID());
        }else{
            return ResultGenerator.genFailResult("人员为空");
        }
        //  在录入人员时，验证手机号是否重复
            Condition condition = new Condition(FnglStaff.class);
            Example.Criteria criteria=condition.createCriteria();
            // 根据删除状态查询列表
            criteria.andEqualTo("delFlag",0);
            List<FnglStaff> staffList = findByCondition(condition);
            if(staffList!=null&&staffList.size()>0){
                for(FnglStaff item : staffList){
                    if(item.getPhone().equals(fnglStaff.getPhone())){
                        return ResultGenerator.genFailResult("手机号已存在，请重新录入");
                    }
                }
            }
        // 新增人员密码时对密码进行MD5加密操作
//        String newpwd = MD5.getMD5(fnglStaff.getPassword());
//        fnglStaff.setPassword(newpwd);
        fnglStaff.setCreateTime(new Date());
        int n = save(fnglStaff);
        if(n>0){
            // 添加人员的时候往用户表对应添加一条用户信息记录
            LrdUser user = new LrdUser();
            user.setCorpCd(CommonConstant.DEFAULT_CORP_CD);
            user.setUserId(fnglStaff.getPhone());
            user.setUserName(fnglStaff.getRealName());
            user.setPassword(MD5.getMD5(fnglStaff.getPassword()));
            user.setSex(fnglStaff.getSex());
            user.setTelNo(fnglStaff.getPhone());
            user.setProjectId(fnglStaff.getProjectId());
            user.setIdNo(fnglStaff.getIdnumber());
            user.setCrtDate(DateTools.formatDate(new Date()));
            // 保存
            int num = lrdUserService.save(user);
            if(num>0){
                // 添加完用户信息后往用户角色关联表添加一条对应记录
                LrdUserrole lrdUserrole = new LrdUserrole();
                lrdUserrole.setCorpCd(CommonConstant.DEFAULT_CORP_CD);
                lrdUserrole.setUserId(user.getUserId());
                lrdUserrole.setRoleId(fnglStaff.getRoleId());
                int number = userRoleServiceImpl.save(lrdUserrole);
                if(number>0){
                    return ResultGenerator.genSuccessResult(fnglStaff);
                }else{
                    return ResultGenerator.genFailResult("添加失败");
                }
            }else{
                return ResultGenerator.genFailResult("添加失败");
            }
        }else{
            return ResultGenerator.genFailResult("添加失败");
        }
    }

    @Override
    @Transactional
    public Result updateFnglStaff(FnglStaff fnglStaff) {

        // 修改密码时也要对密码进行MD5加密操作
//        String newpwd = MD5.getMD5(fnglStaff.getPassword());
//        fnglStaff.setPassword(newpwd);
        fnglStaff.setUpdateTime(new Date());
                // 修改人员表密码时，用户表密码同样改变
                // 先获取到未修改前的人员信息
                FnglStaff fnglStaffBean = findById(fnglStaff.getStaffId());
                // 获取到未修改前的用户信息
                LrdUser lrdUserBean = lrdUserService.findById(fnglStaffBean.getPhone());
                // 删除之前的用户信息
                lrdUserMapper.delete(lrdUserBean);
                // 新增一条新的用户信息
                LrdUser lrdUser = new LrdUser();
                lrdUser.setPassword(MD5.getMD5(fnglStaff.getPassword()));
                lrdUser.setCorpCd(CommonConstant.DEFAULT_CORP_CD);
                lrdUser.setUserId(fnglStaff.getPhone());
                lrdUser.setUserName(fnglStaff.getRealName());
                lrdUser.setSex(fnglStaff.getSex());
                lrdUser.setTelNo(fnglStaff.getPhone());
                lrdUser.setProjectId(fnglStaff.getProjectId());
                lrdUser.setIdNo(fnglStaff.getIdnumber());
                // 保存人员表信息
                 int n = update(fnglStaff);
                 if(n>0){
                // 新增人员信息
                     int save = lrdUserService.save(lrdUser);
                     if(save>0){
                         // 修改人员所属角色或者修改手机号时，用户角色关联表也要改变
                         boolean flag = lrdUserroleMapper.updateLrdUserRole(fnglStaff.getRoleId(),fnglStaffBean.getPhone(),fnglStaff.getPhone());
                         if(flag){
                             return ResultGenerator.genSuccessResult(fnglStaff);
                         }else{
                             return ResultGenerator.genFailResult("更新失败");
                         }
                     }else{
                         return ResultGenerator.genFailResult("更新失败");
                     }
                 }else{
                     return ResultGenerator.genFailResult("更新失败");
                 }
    }

    @Override
    @Transactional
    public Result deleteFnglStaff(String staffId) {
        if(StringUtil.isEmpty(staffId)){
            return ResultGenerator.genFailResult("删除失败，数据为空");
        }
         // 根据人员id获取到对应的人员信息
        FnglStaff fnglStaff = findById(staffId);
        // 获取到手机号也就是登录账号
        String userId = fnglStaff.getPhone();
        if(!StringUtil.isEmpty(userId)){
            // 根据手机号获取到用户信息
            LrdUser lrdUser = lrdUserService.findBy("userId", userId);
            // 根据用户id获取到用户角色关联信息
            LrdUserrole lrdUserrole = userRoleServiceImpl.findBy("userId", userId);
            // 删除用户信息
            lrdUserMapper.delete(lrdUser);
            // 删除用户角色关联信息
            lrdUserroleMapper.delete(lrdUserrole);
        }

        boolean flag = fnglStaffMapper.deleteFnglStaff(staffId);
        if(flag){
            return ResultGenerator.genSuccessResult("删除成功");
        }else{
            return ResultGenerator.genFailResult("删除失败");
        }
    }

    @Override
    @Transactional
    public Result deleteAllFnglStaff(String staffIds) {

        if(!StringUtil.isEmpty(staffIds)){
            String[] staffArr = staffIds.split(",");
            int n = 0;
            for(String item : staffArr){
                if(StringUtil.isEmpty(item)){
                    return ResultGenerator.genFailResult("删除失败，数据为空");
                }
                // 根据人员id获取到对应的人员信息
                FnglStaff fnglStaff = findById(item);
                // 获取到手机号也就是登录账号
                String userId = fnglStaff.getPhone();
                if(!StringUtil.isEmpty(userId)){
                    // 根据手机号获取到用户信息
                    LrdUser lrdUser = lrdUserService.findBy("userId", userId);
                    // 根据用户id获取到用户角色关联信息
                    LrdUserrole lrdUserrole = userRoleServiceImpl.findBy("userId", userId);
                    // 删除用户信息
                    lrdUserMapper.delete(lrdUser);
                    // 删除用户角色关联信息
                    lrdUserroleMapper.delete(lrdUserrole);
                }
                boolean flag = fnglStaffMapper.deleteFnglStaff(item);
                if(flag){
                    n+=1;
                }
            }
            if(n == staffArr.length){
                return ResultGenerator.genSuccessResult("删除成功");
            }else{
                return ResultGenerator.genFailResult("删除失败");
            }
        }else{
            return ResultGenerator.genFailResult("删除失败");
        }
    }
    /**
     *  根据当前登录用户获取到销售人员
     */
    @Override
    public Result getStaff(User user) {

        if(user == null){
            return ResultGenerator.genFailResult("查询失败");
        }
        // 获取到当前登录用户所属角色
        LrdUserrole userrole = userRoleServiceImpl.findBy("userId",user.getUser_id());
        String roleId = userrole.getRoleId();

        Condition condition = new Condition(FnglStaff.class);
        Example.Criteria criteria=condition.createCriteria();
        criteria.andEqualTo("delFlag",0);
        criteria.andEqualTo("roleId",Constants.SALESMAN_ROLE);
        //1.如果是销售人员登录，那么只能看到自己的人员信息
        if(roleId.equals(Constants.SALESMAN_ROLE)){
            criteria.andEqualTo("phone",user.getUser_id());
        }
        //2.如果是项目经理登录，那么可以看到自己项目下所有销售人员信息
        if(roleId.equals(Constants.MANAGER_ROLE)){
            String staffId = getStaffId(user.getUser_id());
            criteria.andEqualTo("blamer",staffId);
        }
        List<FnglStaff> listStaff = findByCondition(condition);
        return  ResultGenerator.genSuccessResult(listStaff);
    }

    /**
     * 根据当前登录用户手机号获取到人员id
     */
    @Override
    public String getStaffId(String phone) {
        String staffId = fnglStaffMapper.getStaffId(phone);
        return staffId;
    }

    /**
     *  人员登记时获取到所有项目经理
     */
    @Override
    public Result getManager() {
        Condition condition = new Condition(FnglStaff.class);
        Example.Criteria criteria=condition.createCriteria();
        criteria.andEqualTo("delFlag",0);
        criteria.andEqualTo("roleId",Constants.MANAGER_ROLE);
        List<FnglStaff> fnglStaffs = findByCondition(condition);
        return  ResultGenerator.genSuccessResult(fnglStaffs);
    }

    /**
     *  获取到所有二手房下边的销售人员
     */
    @Override
    public Result getHouseStaff() {
        Condition condition = new Condition(FnglProject.class);
        Example.Criteria criteria=condition.createCriteria();
        criteria.andEqualTo("delFlag",0);
        criteria.andEqualTo("projectType",Constants.SECONDHANDHOUSE);
        // 获取到所有的二手房项目
        List<FnglProject> fnglProjects = fnglProjectService.findByCondition(condition);
        Condition newcondition = new Condition(FnglStaff.class);
        Example.Criteria newcriteria=newcondition.createCriteria();
        newcriteria.andEqualTo("delFlag",0);
        // 新建集合存放所有二手房门店id
        List<String> list = new ArrayList();
        if(fnglProjects!=null&&fnglProjects.size()>0){
            for(FnglProject item : fnglProjects){
                list.add(item.getProjectId());
            }
            newcriteria.andIn("projectId",list);
        }

        List<FnglStaff> fnglStaffs = findByCondition(newcondition);
        return  ResultGenerator.genSuccessResult(fnglStaffs);
    }
}